﻿#include "TrMarketSpi.h"
#include "TrImpl.h"
#include <iostream>

CTrMarketSpi::CTrMarketSpi()
{
}

void CTrMarketSpi::OnFrontConnected()
{
    m_pTrImpl->OnResponse(Tr_ResponseID::TrOnFrontConnected, nullptr, nullptr);
    CThostFtdcReqUserLoginField ReqUserLoginField;
    memset(&ReqUserLoginField, 0, sizeof(ReqUserLoginField));
    m_ThostFtdcMdApi->ReqUserLogin(&ReqUserLoginField, 0);
    
}

void CTrMarketSpi::OnFrontDisconnected(int nReason)
{
    m_pTrImpl->OnResponse(Tr_ResponseID::TrOnFrontDisconnected, nullptr, nullptr);
}

void CTrMarketSpi::OnHeartBeatWarning(int nTimeLapse)
{
}

void CTrMarketSpi::OnRspUserLogin(CThostFtdcRspUserLoginField* pRspUserLogin, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast)
{
    m_pTrImpl->OnResponse(Tr_ResponseID::TrMarketUserLogin, reinterpret_cast<void*>(pRspUserLogin), reinterpret_cast<void*>(pRspInfo));
    if (!(pRspInfo && (pRspInfo->ErrorID != 0)))
    {
        Subscribe();
    }
}

void CTrMarketSpi::OnRspUserLogout(CThostFtdcUserLogoutField* pUserLogout, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast)
{
}

void CTrMarketSpi::OnRspError(CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast)
{
}

void CTrMarketSpi::OnRspSubMarketData(CThostFtdcSpecificInstrumentField* pSpecificInstrument, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast)
{
}

void CTrMarketSpi::OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField* pSpecificInstrument, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast)
{
}

void CTrMarketSpi::OnRspSubForQuoteRsp(CThostFtdcSpecificInstrumentField* pSpecificInstrument, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast)
{
}

void CTrMarketSpi::OnRspUnSubForQuoteRsp(CThostFtdcSpecificInstrumentField* pSpecificInstrument, CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast)
{
}

void CTrMarketSpi::OnRtnDepthMarketData(CThostFtdcDepthMarketDataField* pDepthMarketData)
{
    m_pTrImpl->OnResponse(Tr_ResponseID::TrOnRtnDepthMarketData, reinterpret_cast<void*>(pDepthMarketData), nullptr);
}

void CTrMarketSpi::OnRtnForQuoteRsp(CThostFtdcForQuoteRspField* pForQuoteRsp)
{
}

void CTrMarketSpi::Subscribe()
{
    unsigned nCount = static_cast<unsigned>(m_pTrImpl->m_ImplSubscribes.size());
    char** ppInstrumentID = new char* [nCount];
    unsigned int nIndex = 0;
    for (unsigned int i = 0; i < nCount; i++)
    {
        ppInstrumentID[nIndex] = new char[13];

        memset(ppInstrumentID[static_cast<int>(i)], '0', sizeof(char*));
        strcpy_s(ppInstrumentID[static_cast<int>(i)], sizeof(ppInstrumentID[static_cast<int>(i)]), m_pTrImpl->m_ImplSubscribes.at(static_cast<unsigned int>(i)).c_str());
        nIndex++;
    }
    m_ThostFtdcMdApi->SubscribeMarketData(ppInstrumentID, static_cast<int>(m_pTrImpl->m_ImplSubscribes.size()));
    delete[] ppInstrumentID;
    ppInstrumentID = nullptr;

}